package com.lu.system.Interceptor;

import com.lu.common.utils.TokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
//        String origin = request.getHeader("Origin");
//        response.setHeader("Access-Control-Allow-Origin", origin);
//        response.setHeader("Access-Control-Allow-Methods", "*");
//        response.setHeader("Access-Control-Allow-Headers","Origin,Content-Type,Accept,token,X-Requested-With");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
        System.out.println("请求URL="+request.getRequestURI().toString());

        if(request.getRequestURI().toString().equals("/mail/systemLogin/login")
                ||request.getRequestURI().toString().equals("/mail/systemLogin/toLoginMsg")){

            return true;
        }


//        String assess_token = httpServletRequest.getHeader("access_token");
        String assess_token =  request.getParameter("access_token");
        if(!StringUtils.isEmpty(assess_token)){

            try {
                Claims claims = TokenUtils.parseJWT(assess_token);
                return true;
            }catch (Exception e){

                //token失效
                request.getRequestDispatcher("/mail/systemLogin/toLoginMsg").forward(request,response);
            }


        }else {

            request.getRequestDispatcher("/mail/systemLogin/toLoginMsg").forward(request,response);
        }


        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
